/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.bayu.controller;

/**
 *
 * @author joep
 */
import com.bayu.common.lib.CommonUtil;
import com.bayu.services.dao.AvgStopTimeDao;
import com.bayu.services.dao.Graph2mlDao;
import com.bayu.services.entity.AvgStopTime;
import com.bayu.services.entity.Graph2ml;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/graph-2ml-input.htm")
public class Graph2mlInput {

    private Graph2mlDao dao;
    private AvgStopTimeDao avgStopTimeDao;

    @Autowired
    public void setAvgStopTimeDao(AvgStopTimeDao avgStopTimeDao) {
        this.avgStopTimeDao = avgStopTimeDao;
    }

    @Autowired
    public void setDao(Graph2mlDao dao) {
        this.dao = dao;

    }

    @RequestMapping(method=RequestMethod.GET)
    public void displayForm(ModelMap map, String id) {
    }

    @RequestMapping(method = RequestMethod.POST)
    public String proccessForm(@ModelAttribute("Graph2ml") Graph2ml g2ml, BindingResult result,ModelMap map, String date,HttpServletRequest req){
            DateFormat formarter = new SimpleDateFormat("yy-MM-dd");
            Date tanggal;


            if(result.hasFieldErrors("date")){
                try {
                    tanggal = formarter.parse(date);
                    g2ml.setDate(tanggal);

                } catch (ParseException ex) {
                    Logger.getLogger(CompInput.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            // List total = this.dao.custom("select count(*) from Graph2ml where date='" + date + "'");

            String[] tempDate = date.split("-");

            List total = this.dao.custom("select count(*) from Graph2ml where MONTH(date)='" + tempDate[1] + "' AND YEAR(date)='"+tempDate[0]+"'");
            String strTotal=total.get(0).toString();


            int c = Integer.valueOf(strTotal).intValue();
            System.out.println(strTotal+"---"+c+"--"+date);
            if(c > 0){
                return "redirect:ErrorDuplicate.html";
            }else{
                 this.dao.save(g2ml);

                 System.out.println("mulai");
                List curAvg = dao.custom("select avg(batasmax) from Graph2ml"+
                             " where YEAR(date) = '"+Integer.toString(CommonUtil.getCurrentYear())+"'");
                List curAvg1 = dao.custom("select avg(frekwensi) from Graph2ml"+
                                 " where YEAR(date) = '"+
                                 Integer.toString(CommonUtil.getCurrentYear()) +"'");
                List curAvg2 = dao.custom("select avg(actualmould)+avg(actualsand) from Graph2ml"+
                                 " where YEAR(date) = '"+
                                 Integer.toString(CommonUtil.getCurrentYear()) +"'");
                List curAvg3 = dao.custom("select avg(actualmould) from Graph2ml"+
                                 " where YEAR(date) = '"+
                                 Integer.toString(CommonUtil.getCurrentYear()) +"'");
                List curAvg4 = dao.custom("select avg(actualsand) from Graph2ml"+
                                 " where YEAR(date) = '"+
                                 Integer.toString(CommonUtil.getCurrentYear()) +"'");

                String strcurAvg = curAvg.get(0).toString();
                String strcurAvg1 = curAvg1.get(0).toString();
                String strcurAvg2 = curAvg2.get(0).toString();
                String strcurAvg3 = curAvg3.get(0).toString();
                String strcurAvg4 = curAvg4.get(0).toString();

                saveAvg(CommonUtil.getCurrentYear(),Double.parseDouble(strcurAvg),"batas max 2ML");
                System.out.println("Rata2 batasMAX 2ML th "+
                    Integer.toString(CommonUtil.getCurrentYear())+" = "+strcurAvg);

                saveAvg(CommonUtil.getCurrentYear(),Double.parseDouble(strcurAvg1),"frekwensi 2ML");
                System.out.println("Rata2 Frekwensi 2ML th "+
                    Integer.toString(CommonUtil.getCurrentYear())+" = "+strcurAvg1);

                saveAvg(CommonUtil.getCurrentYear(), Double.parseDouble(strcurAvg2), "actual 2ML");
                System.out.println("Rata2 Actual 2ML th "+
                    Integer.toString(CommonUtil.getCurrentYear())+" = "+strcurAvg2);

                saveAvg(CommonUtil.getCurrentYear(),Double.parseDouble(strcurAvg3),"actual mould 2ML");
                saveAvg(CommonUtil.getCurrentYear(),Double.parseDouble(strcurAvg4),"actual sand tr 2ML");
                System.out.println("done");
                 return "redirect:view-2ml-data.htm?msg=Data has been updated";
            }

    }

    private void saveAvg(int tahun, double average, String jenis){
        List svAvg = avgStopTimeDao.custom("from AvgStopTime where "+
                "tahun= "+Integer.toString(tahun)+
                " AND jenis='"+jenis+"'");
        AvgStopTime inpAvg;
        if (svAvg.size() > 0) {
            inpAvg = (AvgStopTime)svAvg.get(0);
            this.avgStopTimeDao.delete(inpAvg);
        }
        inpAvg = new AvgStopTime();
        inpAvg.setTahun(tahun);
        inpAvg.setJenis(jenis);
        inpAvg.setAverage(average);

        this.avgStopTimeDao.save(inpAvg);
    }

}
